# Author:: Alexandre Ribeiro de Souza (<alexandre@lumis.com.br>)

action :parse do
  path_arr = new_resource.path.split('/')
  path_arr.delete_at(-1)
  parent_dir = path_arr.join('/')
  
  query = ''
  script = ::File.new("#{parent_dir}/script.sql", 'w')
  
  ::File.open(new_resource.path, "r") do |infile|
    while (line = infile.gets)
      match = false
      line = "#{line.gsub(/\r/, '').gsub(/\n/, '').gsub(/\t/, '').strip}"
      if not line.empty? and not (line.match(/^PRINT/) or line.match(/^--/) or line.match(/^#/))
        if line.match(/^GO/)
          if not query.strip.empty?
            match = true
          end
        else
          query += "#{line} "
          if query.strip.match(/;$/)
            match = true
          end
        end
      end
      if match
        script.puts query.strip
        query = ''
      end
    end
  end
  
  script.close
end
